/*global getA8Top, _wfcurrentUserId */
import $request from '../../../request/index';
import { workflowRequest } from './workflowRequest';
import Vue from 'vue';
import * as Fiber from 'fiber';
const lockProcessIds = [];

export const isAffairValid = (affairId) => {
  var msg = window.callBackendMethod("portalAffairManager", "checkAffairValid", affairId);
  if ($.trim(msg) != '') {
    Fiber.message.warning(msg);
    return false;
  }
  return true;
};



export const doPigeonholeCheck = (ids, pageType, tableId, grid, secretCheck, callback) => {
  window.doPigeonholeCheckCallbackIds = ids;
  window.doPigeonholeCheckCallbackPageType = pageType;
  window.doPigeonholeCheckSecretCallback = secretCheck;
  window.doPigeonholeCallback = callback;
  window.pigeonhole(null, null, null, null, null, "doPigeonholeCheckCallback");
};

window.doPigeonholeCheckCallback = (result) => {
  if (result) {
    if (result != "cancel") {
      var folder = result.split(",");
      var callerResponder = new CallerResponder();
      callerResponder.success = function (jsonObj) {
        if (jsonObj === "" || confirm(jsonObj)) {
          window.doPigeonholeCol(window.doPigeonholeCheckCallbackIds, folder, window.doPigeonholeCheckCallbackPageType, window.doPigeonholeCheckCallbackTableId, window.doPigeonholeCheckCallbackGrid, window.doPigeonholeCheckSecretCallback);
          unlockWorkflow();
        } else {
          unlockWorkflow();
        }
      };

      try {
        callBackendMethod("colManager", "getIsSamePigeonhole", doPigeonholeCheckCallbackIds, folder[0], callerResponder);
      } catch (e) {
        unlockWorkflow();
      }
    } else {
      unlockWorkflow();
    }
  } else {
    unlockWorkflow();
  }
};
window.doPigeonholeCol = (ids, folder, pageType, tableId, grid, secretCallback) => {
  //var cm = new colManager();
  for (var i = 0; i < ids.length; i++) {
    //cm.transPigeonhole(ids[i], folder[0], pageType);
    callBackendMethod("colManager", "transPigeonhole", ids[i], folder[0], pageType);
  }

  if (secretCallback.getCancelData().size() !== 0) {
    secretCallback.messageDialog();
  } else {
    //归档成功
    $.infor($.i18n('collaboration.grid.alert.archiveSuccess'));
  }
  //删除重复的文档
  callBackendMethod("colManager", "transPigeonholeDeleteStepBackDoc", ids, folder[0]);
  window.doPigeonholeCallback();
  for (var i = 0; i < ids.length; i++) {
    var affairId = ids[i];
    try {
      closeOpenMultyWindow(affairId);
    } catch (e) { }
  }
};


export class BatchParam {
  constructor(processId, affairId, objectId, subject) {
    this.processId = processId;
    this.affairId = affairId;
    this.objectId = objectId;
    this.subject = subject;
  }
}
export class SecretCheck {
  constructor(result, operate) {
    this.secretCheckResult = result;
    this.operate = operate;
  }
  getOperate() {
    return this.operate;
  }
  getSuccessAffairIds() {
    var affairIdArray = new Array();
    for (var i = 0; i < this.secretCheckResult.length; i++) {
      if (this.secretCheckResult[i].resultCode === 0) {
        affairIdArray.push(this.secretCheckResult[i].affairId);
      }
    }
    return affairIdArray;
  }
  messageDialog(callback) {
    var ur1 = window._ctxPath + "/collaboration/batchController.do?method=secretBatch";
    var dialog1 = $.dialog({
      url: ur1,
      title: $.i18n('common.system.hint.label'),
      //系统提示
      width: 450,
      height: 310,
      targetWindow: window.getCtpTop(),
      isDrag: true,
      transParams: this,
      closeParam: {
        show: true,
        handler: function () {
          dialog1.close();
          if (callback) {
            callback();
          }
        }
      },
      minParam: {
        show: false
      },
      maxParam: {
        show: false
      },
      buttons: [{
        text: $.i18n('common.button.close.label'),
        //关闭
        handler: function () {
          dialog1.close();
          if (callback) {
            callback();
          }
        }
      }],

    });
  }
  size() {
    return this.secretCheckResult.length;
  }
  getCancelData() {
    var result = new ArrayList();
    for (var i = 0; i < this.secretCheckResult.length; i++) {
      var ele = this.secretCheckResult[i];
      if (ele && ele.resultCode !== 0) {
        result.add(ele);
      }
    }
    return result;
  }
}

export const lockWorkflow = async (processId, currentUserId, action) => {
  let result = [];
  try {
    const args = `managerMethod=lockWorkflow&arguments=${JSON.stringify([processId, currentUserId, action])}`;
    const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=WFAjax&rnd=97448`;
    const [success, error] = await $request({
      url,
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      data: args
    });
    if (success == null || error) {
      result = new Array("false", $.i18n('workflow.wapi.exception.msg002'));
    }
    return result;
  } catch (e) { alert(e.message); }
};

export const unlockWorkflow = () => {
  if (lockProcessIds.length > 0) {
    for (var i = 0; i < lockProcessIds.length; i++) {
      releaseWorkflowByAction(lockProcessIds[i], $.ctx.CurrentUser.id, 14);
    }
    lockProcessIds.length = 0;
  }
};

export const releaseWorkflowByAction = async (processId, currentUserId, action) => {
  let result = [];
  try {
    const args = `managerMethod=releaseWorkflow&arguments=${JSON.stringify([processId, currentUserId, action])}`;
    const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=WFAjax&rnd=97448`;
    const [success, error] = await $request({
      url,
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      data: args
    });
    if (success == null || error) {
      result = new Array("false", $.i18n('workflow.wapi.exception.msg002'));
    }
    return success;
  } catch (e) {
    alert(e.message);
  }
};

/**
   * 流程操作前校验
   * @param processId 流程id
   * @param workitemId itemId
   * @param nodeId  节点id
   * @param caseId  流程caseId
   * @param useNowexpirationTime 是否使用心跳锁的方式加锁 ("true"/"false")
   * @param operation 流程操作的方式(insertNode:加签,assignNode:当前会签,infoNode:知会,deleteNode:减签,repeal:撤销,stepStop:终止,takeBack:取回，specialStepBack：指定回退)
   *
   */
export const onBeforeWorkflowOperationValidate = async (processId, workitemId, nodeId, caseId, useNowexpirationTime, appName, operation, canRepealFinishProcess) => {
  var result = "";
  if (operation == "insertNode") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4InsertNode',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "assignNode") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4AssignNode',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "infoNode") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4InfoNode',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "deleteNode") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4DeleteNode',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "repeal") {
    if (!canRepealFinishProcess) {
      canRepealFinishProcess = "false";
    }
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4Repeal',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName, canRepealFinishProcess],
    });
  } else if (operation == "stepStop") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4StepStop',
      params: [processId, caseId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "takeBack") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4TakeBack',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  } else if (operation == "specialStepBack") {
    result = await workflowRequest({
      managerMethod: 'onBeforeValidate4SpecialStepBack',
      params: [processId, workitemId, nodeId, _wfcurrentUserId, useNowexpirationTime, appName],
    });
  }
  return result;
};

export const executeWorkflowBeforeEvent = ({
  event, bussinessId, affairId, processTemplateId, processId,
  activityId, formData, appName, formAppId, formViewOperation,
  processXml, attribute, commentContent, is4List
}) => {
  var context = new Object();
  context["event"] = event;
  context["formData"] = formData;
  context["mastrid"] = formData;
  context["processTemplateId"] = processTemplateId;
  context["processId"] = processId;
  context["currentActivityId"] = activityId;
  context["bussinessId"] = bussinessId;
  context["affairId"] = affairId;
  context["appName"] = appName;
  context["formAppId"] = formAppId;
  //context["viewId"] = viewId;
  context["formViewOperation"] = formViewOperation;
  // if (!is4List) {
  //   context["matchRequestToken"] = matchRequestToken;
  // }
  context["processXml"] = processXml;

  context["currentNodeLast"] = $("#workflow_thisNodelast_input").val();

  if (!context["businessData"]) {
    context["businessData"] = new Object();
  }

  context["businessData"]["attribute"] = attribute;
  context["businessData"]["commentContent"] = commentContent;

  return executeWorkflowBeforeEventJson(context, is4List);
};

export const generateRandomNumber = () => {
  // 生成前17位的随机数
  let random17 = Math.floor(Math.random() * 100000000000000000);
  // 补零使随机数达到19位
  let random19 = String(random17).padStart(19, '0');
  return random19;
};




let _count = 0;
let hasWorkflowEvent = true;
export const releaseApplicationButtons = () => {
  _count = 0;
};
async function executeWorkflowBeforeEventJson(param, is4List) {
  var defaultOptions = {
    event: "",//执行的事件名
    formData: "", //表单数据id
    mastrid: "", //表单数据id
    processTemplateId: "",//流程的模板id
    processId: "", //流程id
    currentActivityId: "",//当前节点id
    bussinessId: "", //业务数据id(如:summaryId)
    affairId: "", //事项id
    appName: "", //所属分类(collaboration,edoc)
    formAppId: "",//表单id
    formViewOperation: "",//表单视图id
    matchRequestToken: matchRequestToken,
    processXml: "",//流程图
    currentNodeLast: $("#workflow_thisNodelast_input").val(),
    selectTargetNodeId: "",//回退节点
    submitStyleAfterStepBack: "",//指定回退类型: 0:流程重走，1:提交给我
    businessData: {
      attribute: "",//态度
      commentContent: "",//意见
      stepBackType: "normal"//回退类型(normal：普通回退，specifyBack：指定回退，circleBack：环形回退)
    }

  };
  if (is4List) {
    delete defaultOptions.matchRequestToken;
  }

  param = $.extend(defaultOptions, param);

  if (param.processTemplateId == null || param.processTemplateId == "" || hasWorkflowEvent == "false" || hasWorkflowEvent == false) {
    return true;
  }
  const result = await workflowRequest({
    managerMethod: 'executeBeforeEvent',
    params: [param.event, param],
  });
  if (result) {
    if (result.weakBlock) {
      if (confirm(result.alertMessage) == true) {
        releaseApplicationButtons();
        return true;
      } else {
        return false;
      }
    } else if (result.alertMessage) {
      Fiber.message.warning(result.alertMessage);
      return false;
    }
  }
  return true;
}



function validataDeeFormDev(affairid, attitude, failedCallBack) {
  var flag = true;
  if (attitude == "start") {
    try {
      flag = callBackendMethod("formBindExtendClassEventListener", "validataDeeFormDev", affairid, attitude);
    } catch (e) { }
    if (!flag) {
      var dialog2 = $.messageBox({
        'title': $.i18n('dee.Development.fail.info'),
        'type': 100,
        'msg': $.i18n('dee.Development.validate.info'),
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: $.i18n('common.button.close.label'),
          handler: function () {
            if (failedCallBack && failedCallBack != "undefined") {
              failedCallBack();
            }
            dialog2.close();
          }
        }],
        close_fn: function () {
          if (failedCallBack && failedCallBack != "undefined") {
            failedCallBack();
          }
          dialog2.close();
        }
      });
    }
  }
  return flag;
}
export const beforeSubmit = (affairid, attitude, content, object, sucessCallback, failedCallBack, isExecute) => {
  //isExecute 用来判断是否需要执行dee任务，如果多人执行，不是最后一个节点，或者竞争执行不是第一个处理，那就不执行
  if (validataDeeFormDev(affairid, attitude, failedCallBack)) {
    var taskType = callBackendMethod("formBindExtendClassEventListener", "achieveTaskType", affairid, attitude, content, isExecute);
    if (taskType) {
      var ds1;
      if ("ext" == taskType) {	//开发高级-扩展类
        ds1 = callBackendMethod("formBindExtendClassEventListener", "preHandler", affairid, attitude, content);
        if (ds1 && typeof (ds1) == "object") {
          if (ds1[0] == '1') {	//数组下标[0]值为1代表扩展类，数组下标[0]值2代表DEE，有返回代表审核失败，返回null代表正常
            if (object != null) {
              object.close();
            }
            var extContent = ds1[1].replace(/[\r\n]/g, "");	//扩展类返回值
            var dialog = $.dialog({
              url: "${path}/genericController.do?ViewPage=ctp/form/design/eventTip&content="
                + encodeURIComponent(extContent),
              title: $.i18n('dee.Development.Audit.Results'),
              width: 300,
              height: 300,
              closeParam: { show: false },
              buttons: [
                {
                  text: $.i18n('dee.Development.Transfer.audit.opinion'),
                  id: "sure1",
                  handler: function () {
                    if (content != "") {
                      content = content + "\r\n" + "-----------------------------" + "\r\n";
                    }
                    try {
                      setContentDealComment(content + extContent);
                    } catch (e) {
                    }
                    failedCallBack();
                    dialog.close();
                  }
                },
                {
                  text: $.i18n('common.button.cancel.label'),
                  id: "exit1",
                  handler: function () {
                    failedCallBack();
                    dialog.close();
                  }
                }
              ]
            });
          }
        } else {
          sucessCallback();
        }
      } else if ("dee" == taskType) {
        if (!window._hasPlugin("dee")) {
          Fiber.message.warning($.i18n('dee.form.hasplugin.off'));
          failedCallBack();
          return;
        }
        executeDeeTask(null, affairid, attitude, content, null, "false", sucessCallback, failedCallBack);
      } else {
        sucessCallback();
      }
    } else {
      sucessCallback();
    }
  }
};

function executeDeeTask(r, affairid, attitude, content, currentEventId, skipConcurrent, sucessCallback, failedCallBack) {
  var ds1 = callBackendMethod("collaborationFormBindEventListener", "preDeeHandler", affairid, attitude, content, currentEventId, skipConcurrent);
  if (ds1) {
    var blockFormWriteBackJson = ds1["blockFormWriteBackJson"];
    if (blockFormWriteBackJson) {
      var objs = blockFormWriteBackJson;
      // 兼容google浏览器需要下面这一句替换掉google浏览器添加的pre
      objs = objs.replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", "").replace("</pre>", "").replace("<pre>", "");
      var _objs = $.parseJSON(objs);
      if (_objs.success == "true" || _objs.success == true) {
        // 如果当前权限因为高级权限改变，则将改变后的权限id记录在页面中
        if (_objs.viewRight != undefined && $("#rightId").val() != _objs.viewRight) {
          $("#rightId").val(_objs.viewRight);
          $("#img").removeClass("hidden").addClass("hidden");
        }
        _objs = _objs.results;
        if (typeof formCalcResultsBackFill != "undefined") {
          formCalcResultsBackFill(_objs);
        } else if (document.getElementById("zwIframe") != null) {
          document.getElementById("zwIframe").contentWindow.formCalcResultsBackFill(_objs);
        } else {
          document.zwIframe.formCalcResultsBackFill(_objs);
        }
      } else {
        Fiber.message.warning(_objs.errorMsg);
      }
    }

    var hasNext = ds1["hasNext"];
    var retSkipConcurrent = ds1["skipConcurrent"];
    var retCurrentEventId = ds1["currentEventId"];
    var blockInfoMsgType = ds1["blockInfoMsgType"];
    var blockInfoReason = ds1["blockInfoReason"];
    var exception = ds1["exception"];
    if (exception) {
      var dialog2 = $.messageBox({
        'title': $.i18n('dee.Development.fail.info'),
        'type': 100,
        'msg': exception,
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: $.i18n('common.button.close.label'),
          handler: function () {
            if (failedCallBack && failedCallBack != "undefined") {
              failedCallBack();
            }
            dialog2.close();
          }
        }],
        close_fn: function () {
          if (failedCallBack && failedCallBack != "undefined") {
            failedCallBack();
          }
          dialog2.close();
        }
      });
    } else if (blockInfoMsgType == "error") {
      var dialog1 = $.messageBox({
        'title': $.i18n('dee.Development.fail.info'),
        'type': 100,
        'msg': blockInfoReason,
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: $.i18n('common.button.close.label'),
          handler: function () {
            if (failedCallBack && failedCallBack != "undefined") {
              failedCallBack();
            }
            dialog1.close();
          }
        }],
        close_fn: function () {
          if (failedCallBack && failedCallBack != "undefined") {
            failedCallBack();
          }
          dialog1.close();
        }
      });
    } else if (blockInfoMsgType == "info") {
      var dialog = $.messageBox({
        'title': $.i18n('common.caption'),
        'type': 100,
        'msg': blockInfoReason,
        'imgType': 0,
        buttons: [{
          id: 'exit1',
          text: $.i18n('common.button.ok.label'),
          handler: function () {
            if (hasNext == "true") {
              executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
            } else {
              sucessCallback();
            }
            dialog.close(dialog.index);
          }
        }],
        close_fn: function () {
          if (hasNext == "true") {
            executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
          } else {
            sucessCallback();
          }
          dialog.close(dialog.index);
        }
      });
    } else {
      if (hasNext == "true") {
        executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
      } else {
        sucessCallback();
      }
    }
  }
}



export const _designWorkflow = (rows, callback) => {
  if (rows.length < 1) {
    //请选择要编辑的协同
    Fiber.message.warning($.i18n('collaboration.sendGrid.selectColEdit'));
    return;
  }
  if (rows.length > 1) {
    //只能选择一项协同进行编辑
    Fiber.message.warning($.i18n('collaboration.sendGrid.selectOneColEdit'));
    return;
  }
  const firstItem = rows[0];
  const { caseId, processId, deadline, advanceRemind, templeteId, summaryId, flowFinished } = firstItem;
  const checkResult = callBackendMethod("secretAjaxManager", "checkUserSecretLevel", summaryId);
  if (checkResult && checkResult.length > 0) {
    Fiber.message.warning(checkResult);
    return;
  }
  if (flowFinished || flowFinished == 'true' || templeteId) {
    //该流程已结束或为模板流程不允许修改
    Fiber.message.warning($.i18n('collaboration.sendGrid.workFlowEndAndTemplate.notEdit'));
    return;
  }

  console.log("$.ctp.trigger", "beforeDesignWorkflow", firstItem);
  let sendDevelop = $.ctp.trigger('beforeDesignWorkflow', firstItem);
  if (!sendDevelop) return;

  // 构建值
  // $("#processId", editFlowForm).val(processId);
  // $("#deadline", editFlowForm).val(deadline);
  // $("#advanceRemind", editFlowForm).val(advanceRemind);

  const defaultNodeMap = callBackendMethod("colManager", "getColDefaultNode", window._currentUser.loginAccount);
  let fileSecretLevelValue = null;
  if (window.isSecretLevelEnable) {
    const fileSecretLevel = callBackendMethod("appSecretLevelManager", "getSecretLevelById", summaryId);
    if (fileSecretLevel) {
      fileSecretLevelValue = fileSecretLevel.value;
    }
  }
  const options = {
    targetWin: window.parent,
    caseId: caseId,
    processId: processId,
    valueWin: window,
    appName: 'collaboration',
    isTemplate: false,
    flowPermAccountId: window._currentUser.loginAccount,
    defaultPolicyId: defaultNodeMap.defaultNodeName,
    defaultPolicyName: defaultNodeMap.defaultNodeLable,
    accessFileSecretLevel: fileSecretLevelValue,
    scene: 4,
    buttons: [{
      "id": "saveDBOK",
      "callBackFn": callback
    }, {
      "id": "cancel"
    }],
    SPK: "freeFlow",
    NPS: "default"
  };
  showDiagram(options, firstItem);
  return;
};

/**
   * 
   * 打开流程编辑窗口
   * 
   * options = {
   *     targetWin : window,// Window对象， 必填， dialog弹层依赖对象
   *     valueWin : window,// Window对象， 非必填， 工作流值域所在window层级， 不传则同 targetWin
   *     embedIframeObj : iframe,//非dialong方式展现， 直接在当前页面展现的iframe
   *     
   *     appName : "collaboration",//模块名称
   *     
   *     processId : "8873084409352242841",//流程模板ID， processId
   *     oldTemplateId : "8873084409352242841",//模板id， 目前只看到用来选择子流程时过滤自己
   *     
   *     defaultPolicyId : "collaboration", //默认节点权限ID
   *     defaultPolicyName : "协同",//默认节点权限名称
   *     
   *     currentUserId : "-7704680836011635710",//当前登录人员ID，
   *     currentUserName : "xuqw1+",//当前登录人员名称
   *     currentAccountName : "创世纪",//当前登录单位名称
   *     flowPermAccountId ： "-5546493497148422300",//节点权限校验单位ID，目前只有公文有用
   *     
   *     formAppId : "8153854480052077855",//单据ID、表单或者公文单ID
   *     startDefualtRightId : "-7761117042121225097.-6350791176455829286",//表单开始节点默认节点权限
   *     normalDefualtRightId : "-7761117042121225097.814211044810834268",//表单普通节点默认节点权限
   *     
   *     wendanId : "",//公文文单ID
   *     isValidate ： true,//是否需要校验，流程复制的时候
   *     canCopyFlow : 是否能复制流程
   *     selectPeopleExtParams ： ""//选人组件自定义扩展参数
   *     scene : 0|1|2|3|4|5|6;// 设计态[0]:编辑模版流程(单位管理员、表单管理员) |设计态[1]:自由流程(普通人员)
   *     						  |设计态[2]:查看模版流程(普通人员)|运行态[3]:查看(普通人员)
   *     						  |运行态[4]:督办(督办人员)|运行态[5]:管控(管理人员)|[6]指定回退flash显示页面
   *     caseId : "" ,
   *     currentNodeId : "-1111" 当前节点ID,
   *     formMutilOprationIds:"",
   *     showHastenButton : false, 是否显示催办按钮
   *     isHistoryFlag : "true"/"false" 是否是分库的数据
   *     superviseId : "" 
   *     isAdminMangerModel ： true/false 是否是流程管理的页面
   *	 buttons : [{id:"close",callBackFn:function(){}},//数组，显示的按钮
   * 				{id:"cancel",callBackFn:function(){}}, 
   *				{id:"modify",callBackFn:function(){}}，
   * 				{id:"ok",callBackFn:function(){}}， 
   *				{id:"repeal",callBackFn:function(){}}，
   * 				{id:"stop",callBackFn:function(){}}
   * 				{id:"saveDBOK",callBackFn:function(){}}]  //直接保存修改后的信息
   * 
   * 	isSkipNode : 是否是跳过节点模式；
   * 	callBackFn 
   * }
   */
let workflowFlashDialog = null;
async function showDiagram(options, firstItem) {
  // 兼容查不到window
  const { caseId, processId, deadline, advanceRemind, templeteId, summaryId, flowFinished } = firstItem;
  if (!options.valueWin) {
    options.valueWin = window;
  }
  let defaultOptions = {
    isModalDialog: true,
    isHistoryFlag: false,
    isDebugger: false,
    scene: 3,
    caseId: "",
    san: "",
    currentNodeId: "",
    formMutilOprationIds: "",
    showHastenButton: false,
    selectPeopleExtParams: "",
    isTemplate: false,
    targetWin: null,
    valueWin: null,
    title: $.i18n('common.design.workflow.label'), // 编辑流程
    flowPermAccountId: "",
    defaultPolicyId: "",
    defaultPolicyName: "",
    buttons: [{ "id": "close" }], // 默认关闭按钮
    superviseId: "",
    SPK: "default",
    NPS: "default",
    currentUserId: "",
    currentUserName: "",
    masterId: "",
    formAppId: "",
    isAdminMangerModel: false,
    canExePrediction: false,// 是否可以执行流程预测
    needClonedProcessId: "",
    isSkipNode: "false", //是否是跳过节点模式,
    canSetCircleBranch: "true",// 是否允许设置环形流程
    callBackFn: null,
    isCIPModel: false,
    verifyResultXml: "",//校验结果的xml
    immediatelySave: false,
    onlyEditSubProcess: false,
    disableEditSubprocess: false
  };
  defaultOptions.targetWin = getCtpTop();
  defaultOptions.valueWin = getCtpTop();

  // 浏览态，如果没有传参，显示"查看流程图"
  let isView = false;
  if (options.scene == 2 || options.scene == 3) { // 浏览
    isView = true;
  }
  // 根据业务逻辑初始化部分参数
  initParam4Diagram(options, isView);
  options = $.extend(defaultOptions, options);
  // 窗口校验
  _closeFlashDialogBeforeOpen(options.targetWin);
  const wf_v = await workflowRequest({
    managerMethod: 'getSecurityByUserId',
    params: [''],
  });
  if (wf_v) {
    window.wfDiagram_v = wf_v;
  }
  // 为了解决dialog延迟关闭及IE8关闭问题，采用延迟打开窗口的方式
  setTimeout(
    function () {
      var dwidth = $(options.targetWin).width();
      var dheight = $(options.targetWin).height();
      if (dwidth <= 0 || dheight <= 0) {
        dwidth = $(document.body).width();
        dheight = $(document.body).height();
      }
      var myUrl = window._ctxPath
        + '/workflow/designer.do?method=showDiagram';
      myUrl += '&isDebugger=' + options.isDebugger;
      myUrl += '&isModalDialog=' + options.isModalDialog;
      myUrl += '&isTemplate=' + options.isTemplate;
      myUrl += '&formApp=' + (options.formAppId || "");
      myUrl += '&appName=' + options.appName;
      myUrl += '&san=' + options.san;
      myUrl += '&processId=' + options.processId;
      myUrl += '&currentUserId=' + options.currentUserId || window._wfcurrentUserId || "";
      myUrl += '&currentUserName=' + encodeURIComponent(options.currentUserName);
      myUrl += '&currentUserAccountName=' + encodeURIComponent(options.currentAccountName);
      myUrl += '&defaultPolicyId=' + encodeURIComponent(options.defaultPolicyId);
      myUrl += '&defaultPolicyName=' + encodeURIComponent(options.defaultPolicyName);
      myUrl += '&flowPermAccountId=' + options.flowPermAccountId;
      myUrl += '&wendanId=' + (options.wendanId || "-1");
      myUrl += '&isvalidate=false&oldPTId='
        + (options.oldTemplateId == undefined ? ""
          : options.oldTemplateId);
      myUrl += '&startFormViewOperation='
        + options.startDefualtRightId;
      myUrl += '&nodeFormViewOperation='
        + options.normalDefualtRightId;
      myUrl += '&needValidate=' + options.isValidate;
      myUrl += '&canCopyFlow=' + options.canCopyFlow;
      myUrl += '&isHistoryFlag=' + options.isHistoryFlag;
      myUrl += '&caseId=' + options.caseId;
      myUrl += '&currentNodeId=' + options.currentNodeId;
      myUrl += '&formMutilOprationIds='
        + options.formMutilOprationIds;
      myUrl += '&showHastenButton=' + encodeURIComponent(options.showHastenButton);
      myUrl += '&superviseId=' + options.superviseId;
      myUrl += '&selectPeopleExtParams=' + options.selectPeopleExtParams;
      myUrl += '&SPK=' + options.SPK;
      myUrl += '&NPS=' + options.NPS;
      myUrl += '&masterId=' + options.masterId;
      myUrl += '&canExePrediction=' + options.canExePrediction;
      myUrl += '&needClonedProcessId=' + options.needClonedProcessId;
      myUrl += '&CWID=' + options.currentWorkitemId;
      myUrl += '&SD=' + options.splitDisplay;
      myUrl += '&isSkipNode=' + options.isSkipNode;
      myUrl += '&canSetCircleBranch=' + options.canSetCircleBranch;
      myUrl += '&v=' + wfDiagram_v;
      myUrl += '&isCIPModel=' + options.isCIPModel;
      myUrl += '&onlyEditSubProcess=' + options.onlyEditSubProcess;
      myUrl += '&disableEditSubprocess=' + options.disableEditSubprocess;

      var isAdminMangerModel = options.isAdminMangerModel;
      if (!isAdminMangerModel) {
        isAdminMangerModel = options.scene == 5 || options.scene == 4; //管控态，会加锁，FALSH界面可以直接修改流程入库
      }
      if (isAdminMangerModel) {
        myUrl += "&addWorkflowExpirationTimeLock=true";
      }
      if (options.isSuperviseBatch) {
        myUrl += "&isSuperviseBatch=true";
      }
      var lockAction = 1;
      myUrl += '&action=' + lockAction;
      myUrl += CsrfGuard.getUrlSurffix();
      if (options.embedIframeObj) {// 页面嵌入模式
        myUrl += '&openFromIframe=true';
        myUrl += '&scene=' + options.scene;
        $(options.embedIframeObj).attr("src", myUrl);
        return;
      }
      var returnValueWindow = options.targetWin;
      if (options.valueWin) {
        returnValueWindow = options.valueWin;
      }
      var isButtonDisabled = false;
      var resultLock = ["", ""];
      var isLockTrue = false;  //是否真的加锁成功了
      if (isAdminMangerModel) {
        isButtonDisabled = false;
        var caseId = options.caseId;
        var currentUserId = (options.currentUserId || window._wfcurrentUserId || "");
        if (!options.isSuperviseBatch) {//非批处理加锁
          isButtonDisabled = __lockWorkflow(caseId, isButtonDisabled, options.processId, currentUserId);
          if (!isButtonDisabled) {
            isLockTrue = true;
          }
        }
      }

      function __lockWorkflow(caseId, _isButtonDisabled, processId, currentUserId) {
        if (!caseId) {
          return false;
        }
        var caseState = wfAjax.getCaseState(caseId);
        _isButtonDisabled = caseState[0] == 'true' ? true : false;
        if (!_isButtonDisabled) {
          resultLock = lockWorkflowUseNowexpirationTime(processId, currentUserId, lockAction, "true");
          if (resultLock[0] == 'false') {
            _isButtonDisabled = true;
          }
        }
        return _isButtonDisabled;
      }

      //隐藏确定按钮的时候查看默认使用查看模式
      if (!isButtonDisabled) {
        myUrl += '&scene=' + options.scene;
      } else {
        myUrl += '&scene=3';
      }


      workflowFlashDialog = $
        .dialog({
          id: 'workflow_dialog_workflowDesigner_Id',
          isHide: true,
          url: myUrl,
          width: dwidth - 20,
          height: dheight - 100,
          title: options.title,
          targetWindow: options.targetWin,
          transParams: {
            subProcessJson: $("#process_subsetting",
              returnValueWindow.document).val(),
            formId: $("#formId").val(),
            dwidths: dwidth,
            dheights: dheight - 20,
            processIdAndCaseIdAndFormAppIdAndMasterId: options.processIdAndCaseIdAndFormAppIdAndMasterId,
            templateSubject: options.templateSubject,
            workflowRule: $("#process_rulecontent",
              returnValueWindow.document).val(),
            returnValueWindow: returnValueWindow,
            callBackFn: options.callBackFn,
            modifyTotal: options.modifyTotal,
            verifyResultXml: options.verifyResultXml,
            accessFileSecretLevel: options.accessFileSecretLevel,
            openForecastParam: {
              formId: $("#formId").val(),
              templateId: window.systemTemplateId || window.templateId,
              processId: options.processId,
              currentNodeId: options.currentNodeId,
              summaryId: window.summaryId,
              _executePrediction: window._executePrediction
            }
          },
          closeParam: {
            'show': true,
            handler: function () {
              /*if (typeof recoverWorkFlowHistoryData == 'function') {
                recoverWorkFlowHistoryData();
              }*/
              if (isLockTrue) {
                if (!options.isSuperviseBatch) {//批处理解锁
                  releaseWorkflowByAction(options.processId, (options.currentUserId || window._wfcurrentUserId || ""), 1);
                }
              }

            }
          },
          minParam: {
            show: false
          },
          maxParam: {
            show: false
          },
          notCopyReturnValue: true,
          buttons: assembleButtons(options, isButtonDisabled, isLockTrue)
        });

      if (resultLock && resultLock[0] && resultLock[0] == 'false') {
        Fiber.message.warning(resultLock[1]);
      }

    }, 10);
}



// 根据业务逻辑初始化部分参数
function initParam4Diagram(options, isView) {
  if (!options.title) {
    options.title = isView ? $.i18n('workflow.designer.title.readonly') : $.i18n('common.design.workflow.label');
  }
  if (!options.buttons || !options.buttons.length) {
    options.buttons = isView ? [{ "id": "close" }] : [{ "id": "ok" }, { "id": "cancel" }];
  }
}

/**
   * 第二次打开dialog的时候检查一下窗口是否存在，存在则关闭
   */
function _closeFlashDialogBeforeOpen(tWindow) {
  if (workflowFlashDialog) {
    workflowFlashDialog.isHide = false;
    workflowFlashDialog.close(workflowFlashDialog.index);
  } else {
    if (tWindow && $("#workflow_dialog_workflowDesigner_Id", tWindow.document).size() > 0) {
      tWindow.$("#workflow_dialog_workflowDesigner_Id_mask").remove();
      tWindow.$("#workflow_dialog_workflowDesigner_Id").remove();
    }
  }
}

function getBtn(buttons, key) {
  if (buttons) {
    for (var i = 0; i < buttons.length; i++) {
      var btn = buttons[i];
      if (btn.id == key) {
        return btn;
      }
    }
  }
  return null;
}

//组装流程图显示的button
function assembleButtons(options, isButtonDisabled, isLockTrue) {
  var diagramButtons = [];
  if (options.isSkipNode === "true") { //跳过节点的时候，不需要按钮;
    return diagramButtons;
  }
  var cancelBtn = getBtn(options.buttons, "cancel");
  var saveDBOKBtn = getBtn(options.buttons, "saveDBOK");
  var saveDBOKBtnHide = false;
  if (saveDBOKBtn) {
    var text = $.i18n('common.button.ok.label');
    if (options.isSuperviseBatch) {
      text = $.i18n('workflow.designer.page.button.supervise.batch.modify.ok.js');
    }
    var saveDBOKButton = {
      id: 'saveDBOKButton',
      hide: saveDBOKBtnHide,
      btnType: 1,
      isEmphasize: true,
      disabled: isButtonDisabled,
      text: text,
      handler: function () {
        var returnValue = workflowFlashDialog.getReturnValue({
          "innerButtonId": "supervious_ok"
        });

        if (isLockTrue) {
          _releaseLock(options);
        }

        if (returnValue) {

          // 关闭dialog窗口
          _closeOrHideFlashDialog();


          if (saveDBOKBtn && typeof saveDBOKBtn.callBackFn == "function") {
            saveDBOKBtn.callBackFn(returnValue);
          }
        } else {
          // 关闭dialog窗口
          _closeOrHideFlashDialog();
        }
      }
    };
    diagramButtons.push(saveDBOKButton);
  }
  if (cancelBtn) {
    var cancelButtons = {
      text: $.i18n('common.button.cancel.label'),
      handler: function () {
        // 关闭dialog窗口
        _closeOrHideFlashDialog();
        if (typeof recoverWorkFlowHistoryData == 'function') {
          recoverWorkFlowHistoryData();
        }
        if (typeof cancelBtn.callBackFn == "function") {
          cancelBtn.callBackFn(options, workflowFlashDialog);
        }
        if (isLockTrue) {
          releaseWorkflowByAction(options.processId,
            (options.currentUserId || window._wfcurrentUserId || ""), 1);
        }
      }

    };
    diagramButtons.push(cancelButtons);
  }
  return diagramButtons;
}


function _releaseLock(options) {
  var currentUserId = (options.currentUserId || window._wfcurrentUserId || "");
  if (!options.isSuperviseBatch) {//非批处理解锁

    releaseWorkflowByAction(options.processId, currentUserId, 1);
  }
}

/** 关闭flash dialog窗口 * */
function _closeOrHideFlashDialog() {
  if (!$.browser.msie) {
    workflowFlashDialog.close();
  } else {
    workflowFlashDialog.hideDialog();
  }
}

/**
  * @description 将弹出页面的数据初始化到父页面
  * @returnValue 弹出页面返回的数据
  */
function initDialogDataToParentPage(returnValue, returnValueWindow, tWindow) {
  if (returnValueWindow == null) {
    returnValueWindow = tWindow;
  }
  var process_desc_by = returnValue[0];
  var process_xml = returnValue[1];
  var process_info = returnValue[2];
  var process_rulecontent = returnValue[3];
  var process_subsetting = returnValue[4];
  var process_event = returnValue[5];
  var process_properties = returnValue[7];

  var process_desc_by_input = $("#process_desc_by", returnValueWindow.document)[0];
  var process_xml_input = $("#process_xml", returnValueWindow.document)[0];
  var process_info_input = $("#process_info", returnValueWindow.document)[0];
  var process_rulecontent_input = $("#process_rulecontent", returnValueWindow.document)[0];
  var process_subsetting_input = $("#process_subsetting", returnValueWindow.document)[0];
  var process_event_input = $("#process_event", returnValueWindow.document)[0];
  var process_properties_input = $("#process_properties", returnValueWindow.document)[0];

  if (!process_desc_by_input && process_desc_by) {
    showFlashAlert("Error: not found process_desc_by input element in parent page!");
    throw new Error("Error: not found process_desc_by input element in parent page!");
  }
  if (!process_xml_input && process_xml) {
    showFlashAlert("Error: not found process_xml input element in parent page!");
    throw new Error("Error: not found process_xml input element in parent page!");
  }
  if (!process_info_input && process_info) {
    showFlashAlert("Error: not found process_info input element in parent page!");
    throw new Error("Error: not found process_info input element in parent page!");
  }
  if (!process_rulecontent_input && process_rulecontent) {
    alert("Error: not found process_rulecontent input element in parent page!");
    throw new Error("Error: not found process_rulecontent input element in parent page!");
  }
  if (!process_subsetting_input && process_subsetting) {
    showFlashAlert("Error: not found process_subsetting input element in parent page!");
    throw new Error("Error: not found process_subsetting input element in parent page!");
  }
  if (process_desc_by) {
    process_desc_by_input.value = process_desc_by;
  }
  if (process_xml) {
    process_xml_input.value = process_xml;
  }
  if (process_info) {
    $("#process_info", returnValueWindow.document).attr("value", process_info);
    $("#process_info", returnValueWindow.document).trigger("propertychange").trigger("input");


    try {
      $("#process_info", returnValueWindow.document).tokenInput("destroy");//lilong wangchw 0326
      //隐藏协同右侧的常用联系人
      if (typeof (hideCommonContact) != "undefined") {
        hideCommonContact();
      }

    } catch (e) { }
    $("#process_info", returnValueWindow.document).attr("value", process_info);
  }
  try {
    process_rulecontent_input.value = (process_rulecontent == undefined || process_rulecontent == null) ? "" : process_rulecontent;
  } catch (e) {
  }
  if (process_subsetting) {
    process_subsetting_input.value = process_subsetting;
  }
  if (process_event_input) {
    //alert(process_event);
    process_event_input.value = process_event;
  }
  if (process_properties_input) {
    process_properties_input.value = process_properties;
  }

  try {
    var tprocess_desc_by_input = $("#process_desc_by", tWindow.document)[0];
    var tprocess_xml_input = $("#process_xml", tWindow.document)[0];
    var tprocess_info_input = $("#process_info", tWindow.document)[0];
    var tprocess_rulecontent_input = $("#process_rulecontent", tWindow.document)[0];
    var tprocess_subsetting_input = $("#process_subsetting", tWindow.document)[0];
    var tprocess_event_input = $("#process_event", tWindow.document)[0];
    var tprocess_properties_input = $("#process_properties", tWindow.document)[0];

    tprocess_desc_by_input.value = process_desc_by;
    tprocess_xml_input.value = process_xml;
    tprocess_info_input.value = process_info;
    tprocess_rulecontent_input.value = process_rulecontent;
    tprocess_subsetting_input.value = process_subsetting;
    tprocess_event_input.value = process_event;
    tprocess_properties_input.value = process_properties;
  } catch (e) { }
}





/**
 * 表单授权按钮onclick响应 moduleIds:所选表单协同id数组 moduleType:模块类型
 * 使用请参考com.seeyon.ctp.common.ModuleType枚举
 * callBack：授权成功之后的回调方法，可执行刷新页面或者在所选表单协同title之后添加已经授权的图标设置
 */
export const setRelationAuth = (moduleIds, moduleType, callBack, failCallBack) => {
  // 如果只有一条，则查询出此条协同原来授权
  var oldSelect = new Object();
  oldSelect.text = "";
  oldSelect.value = "";
  if (moduleIds.length == 1) {
    var param = new Object();
    param.moduleId = moduleIds[0];
    param.moduleType = moduleType;
    callBackendMethod("formRelationManager", "getRelationAuthorityBySummaryId", param, {
      success: function (_obj) {
        var resultObj = $.parseJSON(_obj);
        if (resultObj.success == "true" || resultObj.success == true) {
          oldSelect = resultObj.oldSelect;
          selectPeopleForRelationAuthority(moduleIds, moduleType, oldSelect, callBack, failCallBack);
        } else {
          Fiber.message.warning(resultObj.errorMsg);
          if (failCallBack) {
            failCallBack();
          }
        }
      }
    });
  } else {
    selectPeopleForRelationAuthority(moduleIds, moduleType, oldSelect, callBack, failCallBack);
  }
};

// 关联授权选人
export const selectPeopleForRelationAuthority = (moduleIds, moduleType, oldSelect, callBack, failCallBack) => {
  $.selectPeople({
    panels: 'Department,Team,Post,RelatePeople,Outworker',
    selectType: 'Account,Member,Department,Team,Post,RelatePeople,Outworker',
    hiddenPostOfDepartment: true,
    params: oldSelect,
    minSize: 0,
    canclecallback: function () {
      if (failCallBack) {
        failCallBack();
      }
    },
    callback: function (ret) {
      var summ = new Object();
      if (ret.value == undefined || ret.value == '') {
        summ.text = '';
        summ.value = '';
      } else {
        summ.text = ret.text;
        summ.value = ret.value;
      }
      summ.moduleIds = moduleIds.join(",");
      summ.moduleType = moduleType;

      callBackendMethod("formRelationManager", "updateRelationAuthority", summ, {
        success: function (_obj) {
          var resultObj = $.parseJSON(_obj);
          if (resultObj.success == "true" || resultObj.success == true) {
            if (summ.value == '') {
              callBack(false);
            } else {
              callBack(true);
            }
          } else {
            Fiber.message.warning(resultObj.errorMsg);
            if (failCallBack) {
              failCallBack();
            }
          }
        }
      });
    }
  });
}



